package com.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.dao.ShippingMapper;
import com.mall.enums.ResponseEnum;
import com.mall.form.ShippingForm;
import com.mall.pojo.Shipping;
import com.mall.service.IShippingService;
import com.mall.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.ws.Response;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 黄建
 * @Date: 2020/1/26 14:41
 */
@Service
public class ShippingServiceImpl implements IShippingService {

    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    public ResponseVo<Map<String, Integer>> add(Integer uid, ShippingForm shippingForm) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(shippingForm,shipping);
        shipping.setUserId(uid);

        int resultCount = shippingMapper.insertSelective(shipping);
        if (resultCount <= 0){
            return ResponseVo.error(ResponseEnum.PASSWORD_ERROR,"新建地址失败");
        }

        Map<String, Integer> shippingId = new HashMap();
        shippingId.put("shippingId", shipping.getId());

        return ResponseVo.success(ResponseEnum.SUCCESS,"新建地址成功",shippingId);
    }

    @Override
    public ResponseVo delete(Integer uid, Integer shippingId) {
        int resultCount = shippingMapper.deleteByUidShippingId(uid, shippingId);
        if (resultCount <= 0){
            return ResponseVo.error(ResponseEnum.DELETE_SHIPPING_FAIL);
        }
        return ResponseVo.success(ResponseEnum.SUCCESS,"删除地址成功");
    }

    @Override
    public ResponseVo update(Integer uid,Integer shippingId,ShippingForm shippingForm) {

        Shipping shipping = shippingMapper.selectByPrimaryKey(shippingId);
        if (shipping == null){
            return ResponseVo.error(ResponseEnum.SHIPPING_NOT_EXIST);
        }
        BeanUtils.copyProperties(shippingForm,shipping);
        shipping.setUserId(uid);

        int resultCount = shippingMapper.updateByUserId(shipping);
        if (resultCount <= 0){
            return ResponseVo.error(ResponseEnum.PASSWORD_ERROR,"地址更新失败");
        }
        return ResponseVo.success(ResponseEnum.SUCCESS,"更新地址成功");
    }

    @Override
    public ResponseVo<PageInfo<Shipping>> list(Integer uid, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<Shipping> shippings = shippingMapper.selectAllByUserId(uid);

        PageInfo<Shipping> pageInfo = new PageInfo<>(shippings);

        return ResponseVo.success(pageInfo);
    }
}
